import { Component, ViewChild } from '@angular/core';

import { Events, AlertController, App, List, ModalController, NavController, NavParams, ToastController, Platform } from 'ionic-angular';

import { Keyboard } from "@ionic-native/keyboard";

import { EmailSendService } from './send.service';

import { ContactChoosePage } from '../../contact/choose/choose.component';

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import { Config } from '../../../providers/config';

import { Storage } from '@ionic/storage';

import { Common } from '../../../providers/common';
import { Content } from 'ionic-angular';


import _ from 'lodash';

@Component({
  selector: 'page-email-send',
  templateUrl: './send.html',
  providers: [EmailSendService]
})
export class EmailSendPage {
	moa_page_name: any = "page-email-send";
  moa_page_explain: any = "写邮件";

  @ViewChild(Content) content: Content;

  // 返回组织结构如下：
  // {
  //   name: "广发基金",
  //   orgid:"gffunds",
  //   reorgid:"0"
  // }

  // 返回岗位信息结构如下：
  // {
  //   name: "董事长",
  //   orgid:"gsld",
  //   titleid:"dsz"
  // }

  // 返回人员信息结构如下：
  // {
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   titleid:"ybyg"
  // }

  // post email data
  email: any = {
    mailbosid: "",
    login: "fengjk",
    // 邮件标题
    bostitle: "",
    // 邮件内容
    content: "",
    // 收件人账号
    recievelist: "",
    // 密送账号
    secretlist: "",
    // 抄送账号
    otherlist: "",
    // 紧急
    urgency: 2,
    // 是否回执
    isreceipt: 0,
    // 附件
    attach: ""
  };

  display_attach: "";

  // 发件人姓名
  name = '';
  // 收件人列表
  recieveList = [];
  // 密送人列表
  secretList = [];
  // 抄送人列表
  otherList = [];

  inputContent: any = "";

  isForward = false;

  isEmailContentFocus = false;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public sendService: EmailSendService,
    private navParams: NavParams,
    private sanitizer: DomSanitizer,
    public config: Config,
    public events: Events,
    public common: Common,
    public toastCtrl: ToastController,
    public storage: Storage,
    public keyboard: Keyboard,
    private plt: Platform
  ) {
    let _this = this;
    this.storage.get('userInfo').then(function(userInfo) {
      _this.name = userInfo.emname;
    });
    let paramData = this.navParams.data;

    this.display_attach = paramData.attach;

    // 判断是否转发
    if (paramData.opType === 'forward') {
      this.isForward = true;
      delete paramData.opType;
    }

    if (paramData.listType === 'draft') {
      this.isForward = true;
      delete paramData.listType;
    }

    this.otherList = this.formatContactData(paramData.otherlist, paramData.othername);
    this.recieveList = this.formatContactData(paramData.recievelist, paramData.recievname);
    this.secretList = this.formatContactData(paramData.secretlist, paramData.secretname);

    this.checkEmail();

    if (paramData.content) {
      console.info(paramData.content);
      this.common.tranformImgLik(paramData.content, true).then(function(formatContent) {
        paramData.content = formatContent;
        _this.inputContent = _this.sanitizer.bypassSecurityTrustHtml(paramData.content);
      });
      // this.inputContent = paramData.content.replace(new RegExp("<br/>", "g"), '\n');
    }
    delete paramData.content;
    // delete paramData.isreceipt;
    this.email = _.assignIn(this.email, paramData);
    console.info(this.email);
    console.info(this.otherList);
    console.info(this.recieveList);

    // let attachStr = "";
    // _.each(this.email.attach.split(";"), function(item, index) {
    //   attachStr = item.split(",")[0] + "::";
    // });
    if (this.plt.is("ios")) {
      this.keyboard.hideKeyboardAccessoryBar(false);
      this.keyboard.disableScroll(true);
    }
  }

  checkEmail() {
    let otherList = this.common.formatContactListData(this.otherList);
    let recieveList = this.common.formatContactListData(this.recieveList);
    let secretList = this.common.formatContactListData(this.secretList);

    console.log("checkEmail", otherList, recieveList, secretList);

    /*let error = "";
    if (recieveList.indexOf("undefined") > -1) {
      this.recieveList = [];
      if (error === "") {
        error += "收件人";
      } else {
        error += "、收件人";
      }
    }
    if (otherList.indexOf("undefined") > -1) {
      this.otherList = [];
      if (error === "") {
        error += "抄送人";
      } else {
        error += "、抄送人";
      }
    }
    if (secretList.indexOf("undefined") > -1) {
      this.secretList = [];
      if (error === "") {
        error += "密送人";
      } else {
        error += "、密送人";
      }
    }
    if (error != "") {
      let message = "手机调用OA接口获取的" + error + "信息有误，请重新选择。";
      let alert = this.alertCtrl.create({
        title: "提示",
        message: message,
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });

      alert.present();
    }*/
  }

  ionViewDidLoad() {
    // this.app.setTitle('EmailSend');

    /**
     * 键盘显示触发
     */
    this.keyboard.onKeyboardShow().subscribe(data => {
      if (this.isEmailContentFocus) {
        this.keyboard.disableScroll(false);
        this.focusEmailContent();
      }
    });

    /**
     * 键盘关闭触发
     */
    this.keyboard.onKeyboardHide().subscribe(data => {
      if (this.isEmailContentFocus) {
        this.keyboard.disableScroll(true);
        this.isEmailContentFocus = false;
        this.content.scrollTop = this.contentScrollTop;
      }

    });

  }

  ionViewDidLeave() {
    if (this.plt.is("ios")) {
      this.keyboard.disableScroll(false);
      this.keyboard.hideKeyboardAccessoryBar(true);
    }
  }

  openFile(id, name) {
    console.info('-----openFile-----' + id);
    this.common.openFile('email', 'normal', id, name, false);
  };

  /**
   * [editEmail 发送 or 保存 ]
   * @param {[type]} type [description]
   */
  editEmail(type) {

    /*if (this.email.attach && this.email.attach != "") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: "由于OA草稿箱接口暂不支持附件，该功能在手机暂未支持。",
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });

      alert.present();
      return;
    }*/


    let that = this;
    this.inputContent = document.getElementById("email-send-input-content").innerHTML + "";
    // console.info(this.inputContent);
    // return ;
    let tips = '';

    if (this.recieveList.length == 0) {
      tips = tips + '收件人    ';
    }


    if (!this.email.bostitle) {
      tips = tips + '主题    ';
    }


    if (!this.inputContent) {
      tips = tips + '邮件正文';
    }

    if (tips) {
      tips = '请填写：' + tips;
      let toast = this.toastCtrl.create({
        message: tips,
        position: 'middle',
        duration: 2000,
        dismissOnPageChange: true
      });
      toast.present();
      return false;
    }

    this.email.recievelist = this.common.formatContactListData(this.recieveList);
    this.email.secretlist = this.common.formatContactListData(this.secretList);
    this.email.otherlist = this.common.formatContactListData(this.otherList);


    this.common.tranformImgLik(this.inputContent, false).then(function(formatContent) {
      that.email.content = formatContent;
      that.email.isreceipt = parseInt(that.email.isreceipt);
      that.email.urgency = parseInt(that.email.urgency);
      console.info(that.email);

      var attids = "";
      if (that.email.attach) {
        _.each(that.email.attach.split(";"), function(item, index) {
          console.log("index", index);
          var a = item.split(',');
          attids = attids + a[0] + "::";
        });
        console.info("attids", attids);
        that.email.attach = attids;
      }

      that.sendService.editEmail(that.email, type).subscribe(data => {
        if (data) {
          console.info(data);
          // 如果是在草稿箱发送的，则删除该邮件
          if (type == 'send' && that.email.status == 0) {
            that.events.publish('email-list:delete', that.email.mailbosid);
            // 删除草稿箱邮件
            that.sendService.deleteEmail(that.email.mailbosid).subscribe(data => {
              console.info('-----------发送成功  删除草稿箱----------');
            });
          } else {
            if (type === "forward" && that.email.status == 0) {
              that.events.publish('email-list:delete', that.email.mailbosid);
              // 删除草稿箱邮件
              that.sendService.deleteEmail(that.email.mailbosid).subscribe(data => {
                console.info('-----------发送成功  删除草稿箱----------');
              });
            }
            that.events.publish('email-list:update', that.email.mailbosid, that.email);
          }
          let alert = that.alertCtrl.create({
            title: '提示',
            subTitle: '操作成功',
            buttons: ['确认']
          });
          alert.present();
          that.navCtrl.pop();
        }
      });
    });
  }

  /**
 * [formatContactData 把CN=A938493525/TI=ybyg/OU=xtyfz 和  系统研发组/一般员工/冯镜蒯 对应上]
 * @param {[type]} code [CN=A938493525/TI=ybyg/OU=xtyfz]
 * @param {[type]} name [系统研发组/一般员工/冯镜蒯]
 */
  formatContactData(code, name) {
    let result = [];
    if (code) {
      code = code.split(',');
      name = name.split(',');
      _.each(code, function(item, index) {
        let contact: any = {};

        _.each(item.split('/'), function(t, i) {
          let temp = t.split('=');
          if (temp[0] == 'CN') {
            contact.empid = temp[1];
          } else if (temp[0] == 'TI') {
            contact.titleid = temp[1];
          } else if (temp[0] == 'OU') {
            contact.orgid = temp[1];
          }
        });

        contact.name = name[index];
        contact.full_name = name[index];
        if (contact.empid) {
          contact.type = 'user';
        } else if (contact.titleid) {
          contact.type = 'title';
        } else {
          contact.type = 'dept';
        }
        result.push(contact);
      });
      return result;
    } else {
      return result;
    }
  }

  /**
   * [chooseUesr 选择用户]
   * @param {[type]} type [description]
   */
  chooseUesr(type) {
    let selected = [];
    if (this[type + "List"].length > 0) {
      selected = this[type + "List"];
    }

    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: selected,
      isSelectUser: false
    });

    modal.present();
    modal.onWillDismiss((data: any[]) => {
      console.info(data);
      if (data) {
        this[type + "List"] = data;
      }
      console.info(this[type + "List"]);
    });
  }

  contentScrollTop = 0;
  focusEmailContent() {
    console.log("focusEmailContent");
    console.log(document.getElementById("dividerEmailContent").offsetTop);
    console.log(this.content.scrollTop);

    if (this.isEmailContentFocus) {
      this.content.scrollTop = this.contentScrollTop + document.getElementById("dividerEmailContent").offsetTop;
      console.log(this.content.scrollTop);
      console.log(document.getElementById("email-send-input-content").offsetTop);
    } else {
      this.isEmailContentFocus = true;
    }
  }

}
